package com.jzr.bedside.db1.service.Impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.jzr.bedside.common.SecurityHelper;
import com.jzr.bedside.db1.dto.FoodOrderDto;
import com.jzr.bedside.db1.mapper.MyFoodOrderMapper;
import com.jzr.bedside.db1.mapper.TFoodOrderDetailMapper;
import com.jzr.bedside.db1.model.TFoodOrder;
import com.jzr.bedside.db1.service.TFoodOrderService;
import com.jzr.bedside.db1.vo.FoodOrderDetailVo;
import com.jzr.bedside.db1.vo.FoodOrderVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.List;

@Service
public class TFoodOrderServiceImpl extends ServiceImpl<MyFoodOrderMapper,TFoodOrder> implements TFoodOrderService {
    @Autowired
    private TFoodOrderDetailMapper foodOrderDetailMapper;

    @Override
    public List<FoodOrderVo> list(FoodOrderDto record) {
        return baseMapper.list(record);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Integer add(FoodOrderVo record) throws Exception {
        LocalDateTime updateDate = LocalDateTime.now();
        Integer userId = SecurityHelper.getUserId();
        record.setUpdateBy(userId);
        record.setUpdateTime(updateDate);
        record.setStatus(1);
        int count = baseMapper.insert(record);
        if(count <= 0){
            throw new Exception("order保存0条记录");
        }
        if(record.getId() == null){
            throw new Exception("获取id为空");
        }
        for(FoodOrderDetailVo detailVo : record.getDetails()){
            detailVo.setUpdateBy(userId);
            detailVo.setUpdateTime(updateDate);
            detailVo.setOrderId(record.getId());
            count = foodOrderDetailMapper.insert(detailVo);
            if(count <= 0){
                throw new Exception("detail保存0条记录");
            }
        }

        return count;
    }

    @Override
    public Integer getStatus(Integer id) {
        QueryWrapper<TFoodOrder> qw = new QueryWrapper<>();
        qw.select("status");
        qw.eq(TFoodOrder.Id_,id);
        TFoodOrder t = baseMapper.selectOne(qw);
        return t.getStatus();
    }

    @Override
    public Integer cancel(Integer id) {
        TFoodOrder foodOrder = new TFoodOrder();
        foodOrder.setId(id);
        foodOrder.setStatus(0);
        return baseMapper.updateById(foodOrder);
    }
}
